package com.example.demo.packageTest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class PackageClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到消息如下");
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, Charset.forName("utf-8")));
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception{
        for(int i = 0;i < 10000;++i){
            String mes = "今天天气冷，吃火锅呀！";
            byte[] content = mes.getBytes("utf-8");
            int length = mes.getBytes("utf-8").length;
            //创建协议包对象
            MessageProtocol protocol = new MessageProtocol();
            protocol.setLen(length);
            protocol.setContent(content);
            ctx.writeAndFlush(protocol);
        }
    }
}
